// index.ts
// 获取应用实例
import request from '../../utils/request'
import Dialog from '@vant/weapp/dialog/dialog'
const app = getApp<IAppOption>()
Page({
    data: {
        globalData: {},
        showCheckBox: false,// 是否显示患者下拉选择框
        showCheckTip: false,// 是否显示选择患者提示语
        patientInfo: {},// 选中的患者信息
        patientList: [],// 患者列表
        
        showKdTip: false,// 是否显示绑定提示语
        
        mattressObj: {},// 设备监测数据
        mattressTimer: 0, //定时器

        showBindDoctor: false, // 绑定医生账号弹框
        yisheng: '',// 医生账号
        password: '',// 医生密码
        popup: {},// 提示框
    },
    onLoad() {

    },
    onShow() {
        this.setData({
            globalData: app.globalData
        })

        this.getPatientList()
    },
    // 患者列表
    getPatientList() {
        if(! app.globalData.userInfo.nickName){
            this.setData({
                showCheckBox: false,
                patientInfo: {},
                mattressObj: {},
                patientList: [],
            });
            clearInterval(this.data.mattressTimer);
            return ;
        }
        request.get('/applet/patient/data', { dataType: app.globalData.dataType }).then((res: any) => {

            let arr = res.data.data;
            this.setData({
                patientList: arr
            });
        
            if (arr && arr.length > 0) {

                let syncInfo = wx.getStorageSync('patientinfo');
                let info;
                if(syncInfo) {
                    info = arr.find(obj => obj.visitNo === syncInfo.visitNo);
                }
                if(! info) {
                    // 取第一个患者
                    info = arr[0];
                }
                this.setData({
                    patientInfo: info
                });

                // 获取监测数据
                this.getBraceletRTD()

                // 定时器每30秒请求一次数据
                this.data.mattressTimer = setInterval(() => {
                    this.getBraceletRTD()
                }, 30000);
            } else {
                this.setData({
                    patientInfo: {},
                    mattressObj: {},
                });
                clearInterval(this.data.mattressTimer);
            }
        })
    },
    // 查询实时数据
    getBraceletRTD() {
        if(! this.data.patientInfo || ! this.data.patientInfo.visitNo) {
            clearInterval(this.data.mattressTimer);
            return ;
        }
        request.get('/applet/equipment/getBraceletRealTimeData', { visitNo: this.data.patientInfo.visitNo }).then((res: any) => {
            this.setData({
                mattressObj: res.data.data
            })
        })
    },

    // 打开/关闭患者选项框
    openCheckBox(){
        let that = this;
        that.setData({ showCheckBox: !that.data.showCheckBox });
        if((!that.data.patientList || that.data.patientList.length == 0) && that.data.showCheckBox) {
            that.setData({ showKdTip: true });
            // 延迟2秒关闭
            setTimeout(() => {
                that.setData({ showKdTip: false });
            }, 2000)
        }
    },
    // 选中患者
    haldCheckPatient(e: any){
        let patientinfo = e.currentTarget.dataset.patientinfo
        this.setData({ 
            patientInfo: patientinfo,
            showCheckBox: false,
        });

        wx.setStorageSync('patientinfo', patientinfo);
        
        // 获取监测数据
        this.getBraceletRTD()
    },

    // 健康报告、历史数据
    toDataPage(e: any){
        let that = this
        if(! app.globalData.userInfo.nickName){
            wx.navigateTo({
                url:'/pages/login/login'
            })
            return ;
        }

        if(!that.data.patientInfo || !that.data.patientInfo.visitNo) {
            // 打开提示
            that.setData({ showCheckTip: true });
            // 延迟2秒关闭
            setTimeout(() => {
                that.setData({ showCheckTip: false });
            }, 5000)
        } else {
            let obj = that.data.patientInfo;
            const url: string = e.currentTarget.dataset.url
            wx.navigateTo({
                url: url + '?visitNo=' + obj.visitNo
            })
        }
    },
    // 登录页面跳转
    handleTo(e: any) {
        if(app.globalData.userInfo.nickName){
            const url: string = e.currentTarget.dataset.url
            wx.navigateTo({
                url: url
            })
        }else{
            wx.navigateTo({
                url:'/pages/login/login'
            })
        }
    },

    // 退出登录
    logOut(){
        let that = this;
        Dialog.confirm({
            title: '确认退出登录吗？',
            confirmButtonColor: "#00A991"
        }).then(() => {
            request.delete('/auth/appLogout').then(res => {
                app.globalData.userInfo = {}
                app.globalData.access_token = ''

                wx.setStorageSync('userInfo', {});
                wx.setStorageSync('access_token', "");
                wx.setStorageSync('doctorAccount', "");
                wx.setStorageSync('patientinfo', "");
                that.setData({
                    globalData: app.globalData
                })
                wx.redirectTo({
                    url: '/pages/index/index',
                });

            })
        }).catch(() => {
            // on cancel
        });
    },

    unbindDoctor(){
        let that = this;
        Dialog.confirm({
            title: '确认要解绑医生账号吗？',
            confirmButtonColor: "#00A991"
        }).then(() => {
            request.delete('/applet/bind-info/unbindDoctor').then(res => {
                app.globalData.doctorAccount = ''
                wx.setStorageSync('doctorAccount', "");
                clearInterval(that.data.mattressTimer);
                that.setData({
                    globalData: app.globalData,
                    patientInfo: {},
                    patientList: [],
                    popup: {
                        idx: Math.random(),
                        show: true,
                        title: '提 示',
                        msg: '医生账号解绑成功！',
                        icon: '../../static/img/smile.png'
                    },
                });
            })
        }).catch(() => {
            // on cancel
        });
    },

    showBind(){
        this.setData({
            showBindDoctor: true,
        });
    },
    onBindClose(){
        this.setData({
            showBindDoctor: false,
            yisheng: '',
            password: '',
        });
    },
    doBindDoctor(){
        let that = this;

        let acc = that.data.yisheng;
        let pwd = that.data.password;
        // 判断参数
        if(! acc){
            wx.showToast({
                title: '请输入医生账号',
                icon: 'error',
                duration: 2000
            })
            return ;
        }
        // 判断参数
        if(! pwd){
            wx.showToast({
                title: '请输入医生密码',
                icon: 'error',
                duration: 2000
            })
            return ;
        }


        wx.showLoading({
            title: '请求中...',
        });

        request.get('/applet/bind-info/bindDoctor', {account: acc, password: pwd}).then((res: any) => {

            wx.hideLoading();
            that.onBindClose();

            // 保存医生账号信息
            app.globalData.doctorAccount = acc;
            wx.setStorageSync('doctorAccount', acc);
            
            that.setData({
                globalData: app.globalData,
                popup: {
                    idx: Math.random(),
                    show: true,
                    title: '提 示',
                    msg: '医生账号绑定成功！',
                    icon: '../../static/img/smile.png'
                },
            });
            
            that.getPatientList();
        })
    },

    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide() {
        clearInterval(this.data.mattressTimer)
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        clearInterval(this.data.mattressTimer)
    },

})
